﻿/*
 * EmeCoder v1.2.1.168
 * 作者：Administrator/JOC-PC
 * 时间：2013-12-18 16:53:50
 * 版权：版权所有 (C) Eme Development Team 2013
*/

﻿using System;
using System.ComponentModel;
using System.Xml.Serialization;
using CuteSprite.Eme.Data.BsdUserCenter;
using CuteSprite.Eme.Data.CRM;
using HmFramework;
using HmFramework.Data;

namespace CuteSprite.Eme.Data.Settlement
{
	/// <summary>结算记录</summary>
	[Serializable]
	[ModelCheckMode(ModelCheckModes.CheckTableWhenFirstUse)]
	public class Settlement : Settlement<Settlement> { }

	/// <summary>结算记录</summary>
	public partial class Settlement<TEntity> : Entity<TEntity> where TEntity : Settlement<TEntity>, new()
	{
		#region 对象操作﻿

		static Settlement()
		{
			// 用于引发基类的静态构造函数，所有层次的泛型实体类都应该有一个
			TEntity entity = new TEntity();
		}

		/// <summary>验证数据，通过抛出异常的方式提示验证失败。</summary>
		/// <param name="isNew"></param>
		public override void Valid(Boolean isNew)
		{
			// 这里验证参数范围，建议抛出参数异常，指定参数名，前端用户界面可以捕获参数异常并聚焦到对应的参数输入框
			//if (String.IsNullOrEmpty(Name)) throw new ArgumentNullException(__.Name, _.Name.DisplayName + "无效！");
			//if (!isNew && ID < 1) throw new ArgumentOutOfRangeException(__.ID, _.ID.DisplayName + "必须大于0！");

			// 建议先调用基类方法，基类方法会对唯一索引的数据进行验证
			base.Valid(isNew);

			// 在新插入数据或者修改了指定字段时进行唯一性验证，CheckExist内部抛出参数异常
			//if (isNew || Dirtys[__.Name]) CheckExist(__.Name);

			// 货币保留6位小数
			if (Dirtys[__.FuelData]) FuelData = Math.Round(FuelData, 6);
			// 货币保留6位小数
			if (Dirtys[__.CustomerPrice]) CustomerPrice = Math.Round(CustomerPrice, 6);
			// 货币保留6位小数
			if (Dirtys[__.DepartmentPrice]) DepartmentPrice = Math.Round(DepartmentPrice, 6);
			// 货币保留6位小数
			if (Dirtys[__.CompanyPrice]) CompanyPrice = Math.Round(CompanyPrice, 6);
			// 货币保留6位小数
			if (Dirtys[__.CustomsDeclarationCost]) CustomsDeclarationCost = Math.Round(CustomsDeclarationCost, 6);
			// 货币保留6位小数
			if (Dirtys[__.FareCustomsHK]) FareCustomsHK = Math.Round(FareCustomsHK, 6);
			// 货币保留6位小数
			if (Dirtys[__.WarehousingTemporary]) WarehousingTemporary = Math.Round(WarehousingTemporary, 6);
			// 货币保留6位小数
			if (Dirtys[__.OtherCost]) OtherCost = Math.Round(OtherCost, 6);
			// 货币保留6位小数
			if (Dirtys[__.Price]) Price = Math.Round(Price, 6);
			// 货币保留6位小数
			if (Dirtys[__.CustomerWeight]) CustomerWeight = Math.Round(CustomerWeight, 6);
			// 货币保留6位小数
			if (Dirtys[__.DepartmentWeight]) DepartmentWeight = Math.Round(DepartmentWeight, 6);
			// 货币保留6位小数
			if (Dirtys[__.SettleWeight]) SettleWeight = Math.Round(SettleWeight, 6);
			// 货币保留6位小数
			if (Dirtys[__.ProtoCustomerWeight]) ProtoCustomerWeight = Math.Round(ProtoCustomerWeight, 6);
			// 货币保留6位小数
			if (Dirtys[__.ProtoDepartmentWeight]) ProtoDepartmentWeight = Math.Round(ProtoDepartmentWeight, 6);
			// 货币保留6位小数
			if (Dirtys[__.ProtoSettleWeight]) ProtoSettleWeight = Math.Round(ProtoSettleWeight, 6);

			if (isNew)
			{
				//if (!Dirtys[__.CreateOn]) { CreateOn = DateTime.Now; }
				CreateOn = DateTime.Now;
			}
			else if (HasDirty)
			{
				//if (!Dirtys[__.ModifiedOn]) { ModifiedOn = DateTime.Now; }
				ModifiedOn = DateTime.Now;
			}
		}

		///// <summary>首次连接数据库时初始化数据，仅用于实体类重载，用户不应该调用该方法</summary>
		//[EditorBrowsable(EditorBrowsableState.Never)]
		//protected override void InitData()
		//{
		//    base.InitData();

		//    // InitData一般用于当数据表没有数据时添加一些默认数据，该实体类的任何第一次数据库操作都会触发该方法，默认异步调用
		//    // Meta.Count是快速取得表记录数
		//    if (Meta.Count > 0) return;

		//    // 需要注意的是，如果该方法调用了其它实体类的首次数据库操作，目标实体类的数据初始化将会在同一个线程完成
		//    HmTrace.WriteDebug("开始初始化{0}[{1}]数据……", typeof(TEntity).Name, Meta.Table.DataTable.DisplayName);

		//    var entity = new Settlement();
		//    entity.OrganizeID = 0;
		//    entity.CustomerID = 0;
		//    entity.SettlementDate = DateTime.Now;
		//    entity.CustomerDiscount = 0;
		//    entity.DepartmentDiscount = 0;
		//    entity.CompanyDiscount = 0;
		//    entity.BusinessCategory = 0;
		//    entity.ExpressNo = "abc";
		//    entity.GoodsCategory = 0;
		//    entity.SettlementSolutionID = 0;
		//    entity.FuelModel = 0;
		//    entity.FuelData = 0;
		//    entity.CustomerPrice = 0;
		//    entity.Description = "abc";
		//    entity.DepartmentPrice = 0;
		//    entity.CustomerAccount = "abc";
		//    entity.CompanyPrice = 0;
		//    entity.CustomsDeclarationCost = 0;
		//    entity.FareCustomsHK = 0;
		//    entity.WarehousingTemporary = 0;
		//    entity.OtherCost = 0;
		//    entity.Price = 0;
		//    entity.CustomerWeight = 0;
		//    entity.DepartmentWeight = 0;
		//    entity.SettleWeight = 0;
		//    entity.ProtoCustomerWeight = 0;
		//    entity.ProtoDepartmentWeight = 0;
		//    entity.ProtoSettleWeight = 0;
		//    entity.Region = "abc";
		//    entity.ExpressRecipient = "abc";
		//    entity.ExpressDepartment = "abc";
		//    entity.ExpressSendPerson = "abc";
		//    entity.ExpressSendDepartment = "abc";
		//    entity.IsDelete = true;
		//    entity.ModifiedOn = DateTime.Now;
		//    entity.ModifiedUserID = 0;
		//    entity.ModifiedBy = "abc";
		//    entity.CreateOn = DateTime.Now;
		//    entity.CreateUserID = 0;
		//    entity.CreateBy = "abc";
		//    entity.SettlementState = "abc";
		//    entity.Insert();

		//    HmTrace.WriteDebug("完成初始化{0}[{1}]数据！", typeof(TEntity).Name, Meta.Table.DataTable.DisplayName);
		//}

		///// <summary>已重载。基类先调用Valid(true)验证数据，然后在事务保护内调用OnInsert</summary>
		///// <returns></returns>
		//public override Int32 Insert()
		//{
		//    return base.Insert();
		//}

		///// <summary>已重载。在事务保护范围内处理业务，位于Valid之后</summary>
		///// <returns></returns>
		//protected override Int32 OnInsert()
		//{
		//    return base.OnInsert();
		//}

		/// <summary>已重载。在事务保护范围内处理业务，位于Valid之后</summary>
		/// <returns></returns>
		protected override Int32 OnInsert()
		{
			//FillCommonInfo();

			//获取揽件人和揽件部门、付款方式
			FillRecipientAndSend(ExpressNo, BusinessCategoryEnum);
			CalculatePice();

			return base.OnInsert();
		}

		/// <summary>已重载。在事务保护范围内处理业务，位于Valid之后</summary>
		/// <returns></returns>
		protected override int OnUpdate()
		{
			// FillCommonInfo();

			CalculatePice();

			return base.OnUpdate();
		}

		/// <summary>填充公司折扣、部门折扣，这两个信息客户端不做填充</summary>
		private void FillCommonInfo()
		{
			if (CompanyDiscount <= 0) { CompanyDiscount = BsdSystemConfig.Current.CompanyDiscount; }
			if (DepartmentDiscount <= 0)
			{
				var organize = BsdOrganize.FindByID(OrganizeID);
				if (organize != null)
				{
					DepartmentDiscount = organize.SettlementDiscount;
				}
			}
		}

		#endregion

		#region 扩展属性﻿

		/// <summary>该公布价方案所属客户</summary>
		[XmlIgnore]
		public BsdCustomer Customer
		{
			get { return Extends.GetExtend<BsdCustomer, BsdCustomer>("Customer", e => BsdCustomer.FindByID(CustomerID)); }
			set { Extends.SetExtend<BsdCustomer>("Customer", value); }
		}

		/// <summary>快件业务类别的枚举扩展属性</summary>
		[XmlIgnore]
		public ExpressBusinessCategory BusinessCategoryEnum
		{
			get { return (ExpressBusinessCategory)BusinessCategory; }
			set { BusinessCategory = (Int32)value; }
		}

		/// <summary>结算货物类别的枚举扩展属性</summary>
		[XmlIgnore]
		public ExpressGoodsCategory GoodsCategoryEnum
		{
			get { return (ExpressGoodsCategory)GoodsCategory; }
			set { GoodsCategory = (Int32)value; }
		}

		#endregion

		#region 扩展查询﻿

		/// <summary>根据运单号和业务类别查找</summary>
		/// <param name="businesscategory">业务类别</param>
		/// <param name="expressNo">运单号</param>
		/// <returns></returns>
		[DataObjectMethod(DataObjectMethodType.Select, false)]
		public static TEntity FindByExpressNo(ExpressBusinessCategory businesscategory, String expressNo)
		{
			ValidationHelper.ArgumentNullOrEmpty(expressNo, "expressNo");

			if (Meta.Count > 1000)
				return Find(new String[] { _.BusinessCategory, _.ExpressNo }, new Object[] { (Int32)businesscategory, expressNo });
			else // 实体缓存
				return Meta.Cache.Entities.Find(e => e.BusinessCategory == (Int32)businesscategory && e.ExpressNo == expressNo);

			// 单对象缓存
			//return Meta.SingleCache[id];
		}

		/// <summary>根据所属客户、结算日期查找</summary>
		/// <param name="customerid">所属客户</param>
		/// <param name="settlementdate">结算日期</param>
		/// <returns></returns>
		[DataObjectMethod(DataObjectMethodType.Select, false)]
		public static EntityList<TEntity> FindAllByCustomerIDAndSettlementDate(Int32 customerid, DateTime settlementdate)
		{
			if (Meta.Count > 1000)
				return FindAll(new String[] { __.CustomerID, __.SettlementDate }, new Object[] { customerid, settlementdate });
			else // 实体缓存
				return Meta.Cache.Entities.FindAll(e => e.CustomerID == customerid && e.SettlementDate == settlementdate);
		}

		/// <summary>根据所属部门、结算日期查找</summary>
		/// <param name="organizeid">所属部门</param>
		/// <param name="settlementdate">结算日期</param>
		/// <returns></returns>
		[DataObjectMethod(DataObjectMethodType.Select, false)]
		public static EntityList<TEntity> FindAllByOrganizeIDAndSettlementDate(Int32 organizeid, DateTime settlementdate)
		{
			if (Meta.Count > 1000)
				return FindAll(new String[] { __.OrganizeID, __.SettlementDate }, new Object[] { organizeid, settlementdate });
			else // 实体缓存
				return Meta.Cache.Entities.FindAll(e => e.OrganizeID == organizeid && e.SettlementDate == settlementdate);
		}

		/// <summary>根据结算日期查找</summary>
		/// <param name="settlementdate">结算日期</param>
		/// <returns></returns>
		[DataObjectMethod(DataObjectMethodType.Select, false)]
		public static EntityList<TEntity> FindAllBySettlementDate(DateTime settlementdate)
		{
			if (Meta.Count > 1000)
				return FindAll(__.SettlementDate, settlementdate);
			else // 实体缓存
				return Meta.Cache.Entities.FindAll(__.SettlementDate, settlementdate);
		}

		/// <summary>根据主键查找</summary>
		/// <param name="id">主键</param>
		/// <returns></returns>
		[DataObjectMethod(DataObjectMethodType.Select, false)]
		public static TEntity FindByID(Int32 id)
		{
			if (Meta.Count > 1000)
				return Find(__.ID, id);
			else // 实体缓存
				return Meta.Cache.Entities.Find(__.ID, id);
			// 单对象缓存
			//return Meta.SingleCache[id];
		}

		#endregion

		#region 高级查询

		// 以下为自定义高级查询的例子

		///// <summary>
		///// 查询满足条件的记录集，分页、排序
		///// </summary>
		///// <param name="key">关键字</param>
		///// <param name="orderClause">排序，不带Order By</param>
		///// <param name="startRowIndex">开始行，0表示第一行</param>
		///// <param name="maximumRows">最大返回行数，0表示所有行</param>
		///// <returns>实体集</returns>
		//[DataObjectMethod(DataObjectMethodType.Select, true)]
		//public static EntityList<TEntity> Search(String key, String orderClause, Int32 startRowIndex, Int32 maximumRows)
		//{
		//    return FindAll(SearchWhere(key), orderClause, null, startRowIndex, maximumRows);
		//}

		///// <summary>
		///// 查询满足条件的记录总数，分页和排序无效，带参数是因为ObjectDataSource要求它跟Search统一
		///// </summary>
		///// <param name="key">关键字</param>
		///// <param name="orderClause">排序，不带Order By</param>
		///// <param name="startRowIndex">开始行，0表示第一行</param>
		///// <param name="maximumRows">最大返回行数，0表示所有行</param>
		///// <returns>记录数</returns>
		//public static Int32 SearchCount(String key, String orderClause, Int32 startRowIndex, Int32 maximumRows)
		//{
		//    return FindCount(SearchWhere(key), null, null, 0, 0);
		//}

		/// <summary>构造搜索条件</summary>
		/// <param name="key">关键字</param>
		/// <returns></returns>
		private static String SearchWhere(String key)
		{
			// WhereExpression重载&和|运算符，作为And和Or的替代
			// SearchWhereByKeys系列方法用于构建针对字符串字段的模糊搜索
			var exp = SearchWhereByKeys(key, null);

			// 以下仅为演示，Field（继承自FieldItem）重载了==、!=、>、<、>=、<=等运算符（第4行）
			//if (userid > 0) exp &= _.OperatorID == userid;
			//if (isSign != null) exp &= _.IsSign == isSign.Value;
			//if (start > DateTime.MinValue) exp &= _.OccurTime >= start;
			//if (end > DateTime.MinValue) exp &= _.OccurTime < end.AddDays(1).Date;

			return exp;
		}

		#endregion

		#region -- 扩展操作 --

		#region - method Create -

		/// <summary>根据运单产生结算记录</summary>
		/// <param name="entity"></param>
		/// <returns></returns>
		private static TEntity Create(TEntity entity)
		{
			var _entity = entity;

			#region 获取公布价方案

			SettlementSolution settlementSolution = null;
			// 首先搜索客户默认的公布价方案
			var customer = BsdCustomer.FindByID(_entity.CustomerID);
			if (customer != null)
			{
				//// 取客户折扣
				//entity.CustomerDiscount = customer.SettlementDiscount;
				settlementSolution = SettlementSolution.FindByID(customer.SettlementSolutionID);
				_entity.CustomerAccount = customer.BackAccount;
			}
			else
			{
				// 所属客户为空，不做结算
				return null;
			}

			// 接下来查询公布价方案数据表有没有所属客户的公布价方案
			if (settlementSolution == null)
			{
				var list = SettlementSolutionAndCustomer.FindAllByCustomerID(_entity.CustomerID);
				if (list != null && list.Count > 0)
				{
					settlementSolution = SettlementSolution.FindByID(list[0].SettlementSolutionID);
				}
			}

			// 使用默认方案
			if (settlementSolution == null) { settlementSolution = SettlementSolution.FindByCode("DS"); }

			_entity.SettlementSolutionID = settlementSolution.ID;

			// 填充计费价格信息、附加费用信息
			if (!FillPriceInfos(_entity, settlementSolution)) { return null; }

			#endregion 获取公布价方案

			return _entity;
		}

		#endregion - method Create -

		#region - method FillPriceInfos -

		/// <summary>填充计费信息，包括燃油计费等</summary>
		/// <remarks>如果参数settlementSolution为空，说明当前结算实体为折扣模式，只获取默认计费方案的价格参数</remarks>
		/// <param name="entity"></param>
		/// <param name="settlementSolution"></param>
		/// <returns></returns>
		private static Boolean FillPriceInfos(TEntity entity, SettlementSolution settlementSolution = null)
		{
			// 获取默认公布价方案
			if (settlementSolution == null)
			{
				settlementSolution = SettlementSolution.FindByCode("DS");
			}

			#region 计费方案、附加费用、计费价格表

			var billingSolution = BillingSolution.FindBySettlementSolutionIDAndBusinessCategoryAndGoodsCategoryAndRegion(settlementSolution.ID,
				 entity.BusinessCategoryEnum, entity.GoodsCategoryEnum, entity.Region);

			//计费方案为空，返回空值
			if (billingSolution == null) { return false; }

			//计费价格
			var billingpric = BillingPrice.FindByID(billingSolution.BillingPriceID);

			//计费价格为空，返回空值
			if (billingpric == null) { return false; }

			//附加费用
			var additionalCost = AdditionalCost.FindByID(billingSolution.BillingPriceID);

			//计费价格为空，返回空值
			if (additionalCost == null) { return false; }

			#region 燃油计费、报关费、过港车费、临时存储费用、其它费用

			entity.FuelModel = additionalCost.FuelModel;
			entity.FuelData = additionalCost.FuelData;
			entity.WarehousingTemporary = additionalCost.WarehousingTemporary;
			entity.CustomsDeclarationCost = additionalCost.CustomsDeclarationCost;
			entity.FareCustomsHK = additionalCost.FareCustomsHK;
			entity.OtherCost = additionalCost.OtherCost;

			#endregion

			var billingPricDetail = BillingPriceDetail.FindByBillingPriceIDAndWeight(billingpric.ID, entity.SettleWeight);

			// 计费价格明细为空，返回空值
			if (billingPricDetail == null) { return false; }

			//获取公司折扣、部门折扣、客户折扣
			entity.DepartmentDiscount = billingPricDetail.DepartmentDiscount;
			entity.CustomerDiscount = billingPricDetail.CustomerDiscount;
			entity.CompanyDiscount = billingPricDetail.CompanyDiscount;
			entity.Price = billingPricDetail.Price;

			#endregion 计费方案

			return true;
		}

		#endregion - method FillPriceInfos -

		#endregion

		#region -- 业务 --

		#region - method CalculatePice -

		/// <summary>计算总金额</summary>
		private void CalculatePice()
		{
			// 所有折扣百分比为0与100等效，相当于没有折扣
			var customerDiscount = CustomerDiscount == 0 ? 1M : ((Decimal)CustomerDiscount / 100M);
			var departmentDiscount = DepartmentDiscount == 0 ? 1M : ((Decimal)DepartmentDiscount / 100M);
			var companyDiscount = CompanyDiscount == 0 ? 1M : ((Decimal)CompanyDiscount / 100M);
			var additionalcost = OtherCost + WarehousingTemporary + CustomsDeclarationCost + FareCustomsHK;

			//判断是否到付运单，如果是到付就不用计算附加费用。
			if (PayType == "到付")
			{
				CustomerPrice = customerDiscount * Price * CustomerWeight;
				DepartmentPrice = departmentDiscount * Price * DepartmentWeight;
				CompanyPrice = companyDiscount * Price * SettleWeight;
			}
			else
			{
				CustomerPrice = customerDiscount * Price * CustomerWeight + additionalcost;
				DepartmentPrice = departmentDiscount * Price * DepartmentWeight + additionalcost;
				CompanyPrice = companyDiscount * Price * SettleWeight;
			}
		}

		#endregion - method CalculatePice -

		#region - method BatchGenerateSettlement -

		/// <summary>根据所选日期范围查询运单批量生成结算记录</summary>
		/// <param name="start"></param>
		/// <param name="end"></param>
		public static void BatchGenerateSettlement(DateTime start, DateTime end)
		{
			Meta.BeginTrans();
			try
			{
				WhereExpression expressExp = null;
				var expressCount = 0;
				var index = 0;
				var batchSize = 500;

				#region OCS专线

				expressExp = Express._.ExpressDate.Between(start, end);
				expressCount = Express.FindCount(expressExp, null, null, 0, 0);
				if (expressCount > 0)
				{
					while (true)
					{
						var size = Math.Min(batchSize, expressCount - index);
						if (size <= 0) { break; }

						var list = Express.FindAll(expressExp, null, null, index, size);
						if ((list == null) || (list.Count < 1)) { break; }
						index += list.Count;

						foreach (var express in list)
						{
							var entity = FindByExpressNo(ExpressBusinessCategory.ExpressOCS, express.CWBNo);
							if (entity == null)
							{
								entity = new TEntity();
								entity.GoodsCategoryEnum = ("SPX" == express.ExpressService) ? ExpressGoodsCategory.SPX : ExpressGoodsCategory.DOX;
								entity.ExpressNo = express.CWBNo;
								entity.BusinessCategoryEnum = ExpressBusinessCategory.ExpressOCS;
								entity.Region = express.ConsigneeCountryCode;
								entity.CustomerID = express.CustomerID;
								entity.OrganizeID = express.OrganizeID;
								entity.SettlementDate = DateTime.Now;

								////获取揽件人,揽件部门
								//var list_expressrecipent = ExpressRecipient.FindAllByExpressID(express.ID);
								//if (list_expressrecipent != null)
								//{
								//  entity.ExpressRecipientPerson = Staff.FindByID(list_expressrecipent[0].StaffID).FullName;
								//  entity.ExpressDepartment = Organize.FindByID(list_expressrecipent[0].OrganizeID).FullName;
								//}

								////获取派件人员，派件部门
								//var list_ExpressSend = ExpressSend.FindAllByExpressID(express.ID);
								//if (list_ExpressSend != null)
								//{
								//  entity.ExpressSendPerson = Staff.FindByID(list_ExpressSend[0].StaffID).FullName;
								//  entity.ExpressSendDepartment = Organize.FindByID(list_ExpressSend[0].OrganizeID).FullName;
								//}

								////获取付款方式
								//entity.PayType = express.PayType == "Collect" ? "到付" : "预付";

								//获取重量，和原始重量
								entity.ProtoSettleWeight = Math.Max(express.SettleWeight, express.SettleVolWeight);
								entity.SettleWeight = Express.FormatWeight(entity.ProtoSettleWeight);
								entity.ProtoCustomerWeight = Math.Max(express.ReceWeight, express.ReceVolWeight);
								entity.ProtoDepartmentWeight = Math.Max(express.ProfitWeight, express.ProfitVolWeight);
								entity.CustomerWeight = Express.FormatWeight(entity.ProtoCustomerWeight);
								entity.DepartmentWeight = Express.FormatWeight(entity.ProtoDepartmentWeight);

								//获取结算信息
								entity = Create(entity);

								if (entity != null) { entity.SaveWithoutValid(); }
							}
						}
					}
				}

				#endregion OCS专线

				//#region 富力经济线

				//index = 0;
				//expressExp = ExpressEconomyLine._.ExpressDate.Between(start, end);
				//expressCount = ExpressEconomyLine.FindCount(expressExp, null, null, 0, 0);
				//if (expressCount > 0)
				//{
				//  while (true)
				//  {
				//    var size = Math.Min(batchSize, expressCount - index);
				//    if (size <= 0) { break; }

				//    var list = ExpressEconomyLine.FindAll(expressExp, null, null, index, size);
				//    if ((list == null) || (list.Count < 1)) { break; }
				//    index += list.Count;

				//    foreach (var express in list)
				//    {
				//      var entity = FindByExpressNo(ExpressBusinessCategory.ExpressEconomyLine, express.CWBNo);
				//      if (entity == null)
				//      {
				//        entity.GoodsCategoryEnum = ("SPX" == express.ExpressService) ? ExpressGoodsCategory.SPX : ExpressGoodsCategory.DOX;
				//        entity.ExpressNo = express.CWBNo;
				//        entity.Region = express.DestinationCode;
				//        entity.CustomerID = express.CustomerID;
				//        entity.OrganizeID = express.OrganizeID;
				//        entity.SettlementDate = DateTime.Now;

				//        //获取揽件人,揽件部门
				//        var list_expressrecipent = ExpressEconomyLineRecipient.FindAllByExpressID(express.ID);
				//        if (list_expressrecipent != null)
				//        {
				//          entity.ExpressRecipientPerson = Staff.FindByID(list_expressrecipent[0].StaffID).FullName;
				//          entity.ExpressDepartment = Organize.FindByID(list_expressrecipent[0].OrganizeID).FullName;
				//        }

				//        //获取派件人员，派件部门
				//        var list_ExpressSend = ExpressEconomyLineSend.FindAllByExpressID(express.ID);
				//        if (list_ExpressSend != null)
				//        {
				//          entity.ExpressSendPerson = Staff.FindByID(list_ExpressSend[0].StaffID).FullName;
				//          entity.ExpressSendDepartment = Organize.FindByID(list_ExpressSend[0].OrganizeID).FullName;
				//        }

				//        //获取付款方式
				//        entity.PayType = express.PayType == "Collect" ? "到付" : "预付";

				//         //获取重量，和原始重量
				//        entity.ProtoSettleWeight = Math.Max(express.SettleWeight, express.SettleVolWeight);
				//        entity.SettleWeight = ExpressEconomyLine.FormatWeight(entity.ProtoSettleWeight);
				//        entity.ProtoCustomerWeight = Math.Max(express.ReceWeight, express.ReceVolWeight);
				//        entity.ProtoDepartmentWeight = Math.Max(express.ProfitWeight, express.ProfitVolWeight);
				//        entity.CustomerWeight = ExpressEconomyLine.FormatWeight(entity.ProtoCustomerWeight);
				//        entity.DepartmentWeight = ExpressEconomyLine.FormatWeight(entity.ProtoDepartmentWeight);

				//        //获取结算信息
				//        entity = Create(entity);

				//        if (entity != null) { entity.SaveWithoutValid(); }
				//      }
				//    }
				//  }
				//}

				//#endregion 富力经济线

				//#region 富力通

				//index = 0;
				//expressExp = ExpressMix._.ExpressDate.Between(start, end);
				//expressCount = ExpressMix.FindCount(expressExp, null, null, 0, 0);
				//if (expressCount > 0)
				//{
				//  while (true)
				//  {
				//    var size = Math.Min(batchSize, expressCount - index);
				//    if (size <= 0) { break; }

				//    var list = ExpressMix.FindAll(expressExp, null, null, index, size);
				//    if ((list == null) || (list.Count < 1)) { break; }
				//    index += list.Count;

				//    foreach (var express in list)
				//    {
				//      var entity = FindByExpressNo(ExpressBusinessCategory.ExpressMix, express.CWBNo);
				//      if (entity == null)
				//      {
				//        entity.GoodsCategoryEnum = ("SPX" == express.ExpressService) ? ExpressGoodsCategory.SPX : ExpressGoodsCategory.DOX;
				//        entity.ExpressNo = express.CWBNo;
				//        entity.Region = express.ConsigneeCountryCode;
				//        entity.CustomerID = express.CustomerID;
				//        entity.OrganizeID = express.OrganizeID;
				//        entity.SettlementDate = DateTime.Now;

				//        //获取揽件人,揽件部门
				//        var list_expressrecipent = ExpressMixRecipient.FindAllByExpressID(express.ID);
				//        if (list_expressrecipent != null)
				//        {
				//          entity.ExpressRecipientPerson = Staff.FindByID(list_expressrecipent[0].StaffID).FullName;
				//          entity.ExpressDepartment = Organize.FindByID(list_expressrecipent[0].OrganizeID).FullName;
				//        }

				//        //获取派件人员，派件部门
				//        var list_ExpressSend = ExpressMixSend.FindAllByExpressID(express.ID);
				//        if (list_ExpressSend != null)
				//        {
				//          entity.ExpressSendPerson = Staff.FindByID(list_ExpressSend[0].StaffID).FullName;
				//          entity.ExpressSendDepartment = Organize.FindByID(list_ExpressSend[0].OrganizeID).FullName;
				//        }

				//        //获取付款方式
				//        entity.PayType = express.PayType;

				//        //获取重量，和原始重量
				//        entity.ProtoSettleWeight = Math.Max(express.SettleWeight, express.SettleVolWeight);
				//        entity.SettleWeight = ExpressMix.FormatWeight(entity.ProtoSettleWeight);
				//        entity.ProtoCustomerWeight = Math.Max(express.ReceWeight, express.ReceVolWeight);
				//        entity.ProtoDepartmentWeight = Math.Max(express.ProfitWeight, express.ProfitVolWeight);
				//        entity.CustomerWeight = ExpressMix.FormatWeight(entity.ProtoCustomerWeight);
				//        entity.DepartmentWeight = ExpressMix.FormatWeight(entity.ProtoDepartmentWeight);

				//        //获取结算信息
				//        entity = Create(entity);

				//        if (entity != null) { entity.SaveWithoutValid(); }
				//      }
				//    }
				//  }
				//}

				//#endregion 富力通

				Meta.Commit();
			}
			catch (Exception ex)
			{
				Meta.Rollback();
				throw ex;
			}
		}

		#endregion - method BatchGenerateSettlement -

		#region - 获取揽件人员、揽件部门 -

		private void FillRecipientAndSend(String expressNo, ExpressBusinessCategory category)
		{
			switch (category)
			{
				case ExpressBusinessCategory.ExpressOCS:
					//获取揽件人,揽件部门
					var express = Express.FindByCWBNo(expressNo);
					Int32 id = express.ID;
					var list_expressrecipent = ExpressRecipient.FindAllByExpressID(id);
					if (list_expressrecipent != null && list_expressrecipent.Count != 0)
					{
						ExpressRecipientPerson = Staff.FindByID(list_expressrecipent[0].StaffID).FullName;
						ExpressDepartment = Organize.FindByID(list_expressrecipent[0].OrganizeID).FullName;
					}

					//获取派件人员，派件部门
					var list_ExpressSend = ExpressSend.FindAllByExpressID(id);
					if (list_ExpressSend != null && list_ExpressSend.Count != 0)
					{
						ExpressSendPerson = Staff.FindByID(list_ExpressSend[0].StaffID).FullName;
						ExpressSendDepartment = Organize.FindByID(list_ExpressSend[0].OrganizeID).FullName;
					}
					//获取付款方式
					PayType = express.PayType == "Collect" ? "到付" : "预付";
					break;

				case ExpressBusinessCategory.ExpressEconomyLine:

					break;

				case ExpressBusinessCategory.ExpressMix:

					break;
			}
		}

		#endregion

		#endregion -- 业务 --
	}
}